#include"LFMPostDataBuilder.h" 

#include"Song.h"

#include<QCryptographicHash>
#include<QStringList>

const QString LFMPostDataBuilder::API_KEY = "d6e7a2bbdcb6dbb247e9ac78e848d15f";
const QString LFMPostDataBuilder::SECRET_KEY = "d947160c4f1b2b762fc9727f2e6f71a9";

LFMPostDataBuilder::LFMPostDataBuilder(const QString &sessionKey){
	setSessionKey(sessionKey);
}
	
void LFMPostDataBuilder::setSessionKey(const QString &sessionKey){
	m_sessionKey = sessionKey;
}

QString LFMPostDataBuilder::buildAuthData(const QString &methodName, const QString &token){
	QString ret = "method=";
	ret.append(methodName);
	ret.append('&');
	ret.append("api_key=");
	ret.append(API_KEY);
	if(!token.isEmpty()){
		ret.append("&token=");
		ret.append(token);
		QString sig = signature(ret);
		ret.append("&api_sig=");
		ret.append(sig);
	}
	return ret;
}

QString LFMPostDataBuilder::build(const QString &methodName, QPointer<Song> song, unsigned params, const QString &timestamp){
	if(!canScrobble() || song == 0)
		return QString();
	if(song->title().isEmpty() || song->artist().isEmpty())
		return QString();
	
	QString ret = "method=";
	ret.append(methodName);
	ret.append('&');
	
	if(params & TRACK){
		ret.append("track=");
		ret.append(song->title().replace('&', "%26"));
		ret.append('&');
	}
	if(params & ARTIST){
		ret.append("artist=");
		ret.append(song->artist().replace('&', "%26"));
		ret.append('&');
	}
	if(params & ALBUM){
		if(!song->album().isEmpty()){
			ret.append("album=");
			ret.append(song->album().replace('&', "%26"));
			ret.append('&');
		}
	}
	if((params & TIMESTAMP) && !timestamp.isEmpty()){
		ret.append("timestamp=");
		ret.append(timestamp);
		ret.append('&');
	}
	ret.append("api_key=");
	ret.append(API_KEY);
	
	if(params & SESSION_KEY){
		ret.append("&sk=");
		ret.append(m_sessionKey);
	}
	
	if(params & SIGNATURE){
		QString sig = signature(ret);
		ret.append("&api_sig=");
		ret.append(sig);
	}
	return ret;
}

QString LFMPostDataBuilder::signature(const QString &postData){
	QStringList strl = postData.split('&', QString::SkipEmptyParts);
	strl.sort();
	
	QString temp = "";
	QStringList strl2;
	for(int i = 0; i < strl.size(); i++){
		strl2 = strl[i].split('=');
		temp.append(strl2[0]);
		temp.append(strl2[1]);
	}
	temp.append(SECRET_KEY);
	temp.replace("%26", "&");
	QByteArray ba = QCryptographicHash::hash( temp.toUtf8().data(), QCryptographicHash::Md5 );
	return QString(ba.toHex().data());
}
